package com.example.loginmvvm

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.example.loginmvvm.base.BaseActivity
import com.example.loginmvvm.controller.LoginPresenter
import com.example.loginmvvm.interfaces.OnCheckUserNameStateResultCallback
import com.example.loginmvvm.interfaces.OnDoLoginStateChange

class MainActivity : BaseActivity(), OnDoLoginStateChange, OnCheckUserNameStateResultCallback {

    lateinit var etUser: EditText
    lateinit var etPass: EditText
    lateinit var btnLogin: Button
    lateinit var tvStatus: TextView

    private val loginController by lazy {
        LoginPresenter()
    }

    private var isUserNameCanBeUse = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initListener()
    }

    private fun initListener() {
        btnLogin = findViewById(R.id.btn_login)
        etUser = findViewById(R.id.et_user)
        etPass = findViewById(R.id.et_pass)
        tvStatus = findViewById(R.id.tv_status)

        btnLogin.setOnClickListener {
            //去进行登录
            toLogin()
        }

        etUser.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                //检查当前账户是否已注册
                loginController.checkUserNameState(s.toString(), this@MainActivity)
            }

        })
    }

    /**
     * 处理登录逻辑
     */
    private fun toLogin() {
        //做登录的逻辑处理
        val user = etUser.text.toString()
        val pass = etPass.text.toString()

        if (!isUserNameCanBeUse) {
            //提示用户说当前账号已注册
            return
        }

        //进行登录,此操作为异步
        loginController.doLogin(user, pass, this)
        //禁止按钮点击
        //btnLogin.isEnabled = false
    }

    override fun onAccountFormatError() {
        tvStatus.text = "账号为空..."
    }

    override fun onPasswordEmpty() {
        tvStatus.text = "密码为空..."
    }

    override fun onLogin() {
        Log.i("chen", "onLogin: ")
        tvStatus.text = "登录中..."
    }

    override fun onLoginSuccess() {
        Log.i("chen", "onLoginSuccess: ")
        tvStatus.text = "成功..."
    }

    override fun onLoginFailed() {
        Log.i("chen", "onLoginFailed: ")
        tvStatus.text = "失败..."
    }

    override fun onNotExist() {
        //用户名可用
        tvStatus.text = "该用户名可用..."
        isUserNameCanBeUse = true
    }

    override fun onExist() {
        //用户名不可用
        tvStatus.text = "该用户名不可用..."
        isUserNameCanBeUse = false
    }
}